//app.js
var wh = require("utils/wh.js");
App({
  // 微信登录
  wlogin: function (userInfo) {
    let that = this;
    wx.getExtConfig({
      success: function (res) {
        module.exports.globalData = res.extConfig;
        //进行微信登录
        wx.login({
          success: function (res) {
            if (res.code) {
              let data = { code: res.code, encryptedData: userInfo.encryptedData, iv: userInfo.iv, rawData: userInfo.rawData, signature: userInfo.signature };
              wh.Post('/api/user/login', data, function (info) {//登录成功返回的信息
                let userinfo = JSON.stringify(info);
                wx.setStorageSync('W_Userinfo', userinfo);//存储
                wx.setStorageSync('employId', info.id);
                wx.setStorageSync('whlw_app_id', module.exports.globalData.app_id);
                //由于这里是网络请求，可能会在 Page.onLoad 之后才返回 所以此处加入 callback 以防止这种情况
                if (that.employIdCallback) {
                  that.employIdCallback(info.id);
                }
                return true;
              });
            }
          },
          fail: function () {
            return false;
          }
        })
      }
    });
  },
  app_auth: function (self) {
    self.selectComponent("#auth").onCheck()
    let mobile_validate = wx.getStorageSync('mobile_validate')
    let employId = wx.getStorageSync('employId')
    let that = self
    if (employId != '' && employId != undefined) {
      if (mobile_validate != 1) {
        let personUrl = '/api/shop.ajax/person_info';
        wh.Post(personUrl, '', function (res) {
          that.selectComponent("#mobile_auth").onCheckMobile(res.mobile_validated)
        });
      } else {
        that.selectComponent("#mobile_auth").onCheckMobile(1)
      }
    }
  },
  /**
 * 海报
 */
  startToDraw: function (param, url, tag, imgUrl) {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff");
    context.fillRect(0, 0, 375, 667);

    context.setShadow(0, 0, 15, '#e0e0e0');
    context.setStrokeStyle("#e0e0e0");
    context.rect(27, 40, 321, 430);
    context.stroke();
    // context.setGlobalAlpha(0.5);
    context.drawImage(param.path1, -25, 0, 425, 207);
    // context.setGlobalAlpha(1);
    context.drawImage(param.path1, 27, 40, 321, 281);

    // 商品标题
    let goods_name = param.title;

    let g_result = that.breakLinesForCanvas(context, goods_name || ' ', 150, 0);
    let goods_name_str = g_result[0];
    if (g_result.length > 1) {
      goods_name_str += '...';
    }
    context.setFontSize(15);
    context.setFillStyle('#000');
    context.setTextAlign('center');
    context.fillText(goods_name_str, 185, 350);

    // 商品简介
    let goods_brief = param.goods_desc;
    let result = that.breakLinesForCanvas(context, goods_brief || ' ', 250, 0);
    let goods_brief_str = result[0];
    if (result.length > 1) {
      goods_brief_str += '...';
    }
    context.setFontSize(14);
    context.setFillStyle('#333333');
    context.setTextAlign('center');
    context.fillText(goods_brief_str, 185, 370);

    // 商品价格
    let goods_price = '￥' + param.price;
    context.setFontSize(14);
    context.setFillStyle('red');
    context.setTextAlign('center');
    context.fillText(goods_price, 185, 400);


    // 商品原价
    let or_goods_price = '￥' + param.market_price;
    context.setFontSize(14);
    context.setFillStyle('#333333');
    context.setTextAlign('center');
    context.fillText(or_goods_price, 185, 420);

    // 删除线
    context.setStrokeStyle("#333333");
    context.beginPath();//开始一个新的路径  
    context.moveTo(165, 415);//路径的起点  
    context.lineTo(210, 415);//路径的终点  
    context.stroke();//对当前路径进行描边  
    context.closePath();//关闭当前路径  

    if (tag) {
      // 标签
      context.setFillStyle("#ce0000");
      context.fillRect(220, 390, 50, 30);
      // 标签名称
      context.setFontSize(14);
      context.setFillStyle('#fff');
      context.fillText(tag, 245, 410);
    }

    // 二维码
    context.setTextAlign('center');
    context.drawImage(param.path2, 125, 490, 120, 120);
    context.setFontSize(15);
    context.setFillStyle('#000');
    context.setTextAlign('center');
    context.fillText('长按扫码有惊喜', 185, 630);

    context.setFillStyle("#fff");

    context.draw();

  },
  findBreakPoint: function (text, width, context) {
    if (!text || text == '') {
      text = ' ';
    }
    var min = 0;
    var max = text.length - 1;
    while (min <= max) {
      var middle = Math.floor((min + max) / 2);
      var middleWidth = context.measureText(text.substr(0, middle)).width;
      var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
      if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
        return middle;
      }
      if (middleWidth < width) {
        min = middle + 1;
      } else {
        max = middle - 1;
      }
    }

    return -1;
  },
  breakLinesForCanvas: function (context, text, width, font) {
    if (!text || text == '') {
      text = ' ';
    }
    let that = this;
    var result = [];
    if (font) {
      context.font = font;
    }
    var textArray = text.split('\r\n');
    for (let i = 0; i < textArray.length; i++) {
      let item = textArray[i];
      var breakPoint = 0;
      while ((breakPoint = that.findBreakPoint(item, width, context)) !== -1) {
        result.push(item.substr(0, breakPoint));
        item = item.substr(breakPoint);
      }
      if (item) {
        result.push(item);
      }
    }
    return result;
  }
});
